import requests
import json
from pyquery import PyQuery as jq
import execjs
import base64
import urllib   #下载音乐的库
url = "http://www.aigei.com/sound/class/?order=last&page=4"
data = ""
headers = json.loads(r'''{
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Connection": "keep-alive",
    "Content-Length": "337",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Cookie": "gei_d_u=8578bef35b3f4bfaad4e117e4c2a6b85; oOO0OO0oOO00oo0o=true; geiweb-v=zZ+S93HA1QeA2Q6DYTRy5TQz0yEBzxT1Dyh6SZIjMWpyuUV5ZhD/qDUpyxv5xnOE; wueiornjk234kj=d8c2626028a64247bbc0a712cae2a200; JSESSIONID=42AC8A728961A0021C9A0AEAF7218CD3; OooOO000oOOO00o=7356761",
    "Host": "www.aigei.com",
    "Origin": "http://www.aigei.com",
    "Referer": "http://www.aigei.com/sound/class/?order=last&page=1",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
    "X-Requested-With": "XMLHttpRequest"
}''')
lists = []

def save_mp3(itemid,ftype,extime,token):
	node = execjs.get(execjs.runtime_names.PhantomJS)
	jsstr = ""
	for item in ['jquery.min.js','aigei.js']:
	    with open(item,"r") as f:
	        jsstr+=f.read()
	ctx = node.compile(jsstr)	#audio_mp3		2222154		   1534208400547  1ca62daebe
	# data1 = ctx.call('dfu',"audio_mp3","31731353","1533988800890","f093181feb",'','','','')
	data1 = ctx.call('dfu',ftype,itemid,extime,token,'','','','')
	data2 = ctx.call('cqbj',data1)
	resp = requests.post("http://www.aigei.com/f/d/", data=data2, headers=headers)
	message = json.loads(resp.text)['message']
	urls = base64.b64decode(message)
	urllib.request.urlretrieve(urls.decode('utf-8'),f'{itemid}.mp3')

try:
	for i in range(1,10000):
		print(f'第{i}页')
		urls = "http://www.aigei.com/sound/class/?order=last&page=" + str(i);
		resp = requests.get(urls, data=data, headers=headers)
		aa = jq(resp.text)('.main-container-screen-narrow > #res-tab-content > .item-info-list-box.item-info-list-body > .unit-container-list.item-info-list-content > ul')
		for i in aa.items():
			title = i('li > .audio-item-row.audio-item-row1 > .title > span').attr('title')
			types  = i('li > .audio-item-row.audio-item-row2 > .audio-info-dir-group').text()
			itemid = i('li > input').attr('itemid')
			ftype = i('li > input').attr('ftype')
			extime = i('li > input').attr('extime')
			token = i('li > input').attr('token')
			save_mp3(itemid,ftype,extime,token)
			list1 = [title,types,itemid]
			lists.append(list1)
	with open('aikan.txt','w',encoding='utf-8') as f:
		f.write(str(lists))
except Exception as e:
	with open('aikan.txt','w',encoding='utf-8') as f:
		f.write(str(lists))
	raise e



